package com.cw.util;

import java.io.*;
import java.util.*;
import java.util.stream.*;
import javax.annotation.*;
import org.springframework.beans.factory.annotation.*;
import org.springframework.stereotype.*;
import org.springframework.web.multipart.*;

/**
 * @Description:上传当前本地服务器，可以立即回显和获取，（如图片上传立即加载），如不需立即回显请使用ItemFtp工具类
 * @Author: wzw
 * @Time: 2020/12/15 9:14
 */
@Component
public class UploadUtils {

    private UploadUtils() {
    }

    private static String path = "";
    @Value("${upload}")
    private String filePath;

    /**
     * 单文件文件保存到当前服务器
     *
     * @param file 文件
     * @return 新文件名称
     * @Author: wzw
     * @Date: 2020/12/15 10:59
     */
    public static String uploadOne(MultipartFile file) {
	  final String fileId = UUIDUtil.uuid();
	  final String originalFilename = file.getOriginalFilename();
	  final String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
	  final String saveFileName = fileId + suffix;
	  File newFile = new File(path + saveFileName);
	  final boolean exists = newFile.exists();
	  if (!exists) {
		newFile.mkdirs();
	  }
	  try {
		file.transferTo(newFile);
	  } catch (IOException e) {
		return "文件上传失败";
	  }
	  return saveFileName;
    }

    /**
     * 多文件上传
     *
     * @param file
     * @return
     * @throws IOException
     */
    public static List<String> uploadOne(List<MultipartFile> file) throws IOException {
	  return file.stream().map(UploadUtils::uploadOne).collect(Collectors.toList());
    }

    @PostConstruct
    private void init() {
	  path = filePath;
    }
}
